import { t } from 'i18next'
import createVanilla from 'zustand/vanilla'
import create from 'zustand'
import { fetchGetRecordPlayInfo, fetchPostRecordProgress } from '@/api/manager/playVideo'
import { FetchPlayVideoFile, FetchPlayVideoInfo } from '@/api/manager/playVideo/interface'
import { useMccStore } from '../../store'
import Alert, { confirmModal } from '@/components/Alert'
import { store as mccStore } from '@/pages/manager/store'
import {
	getPercent,
	pauseMeetingPlayback,
	resumeMeetingPlayback,
	startMeetingPlayback,
	stopMeetingPlayback,
	stopMix,
	voiceInspire,
	voiceInspireAndStopMix,
} from './utils'
// import { PlayVideoBackInfoProps } from './interface'
type PlayVideoStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	fetchInfo: (flag?: boolean) => void
	setSelectVideoFile: (row: FetchPlayVideoFile | null) => void
	setInfo: (videoInfo: FetchPlayVideoInfo) => void
	changePlayStatus: (videoInfo: FetchPlayVideoInfo) => void
	setProgress: (data: number) => void
	onDragProgress: (data: string) => void
	/**点击开始放像按钮 */
	onStartPlay: () => void
	/**点击停止放像按钮 */
	onStopPlay: () => void
	/**点击暂停放像按钮 */
	onPausePlay: () => void
	/**开始放像 */
	startPlay: (duration: string) => void
	stopPlay: () => void
	pausePlay: () => void
	checkConflict: (callback: () => void) => void
	onContinuePlay: () => void
	isClearTimer: () => void
}
type StateStore = {
	info: FetchPlayVideoInfo
	selectVideoFile: null | FetchPlayVideoFile
	progress: number
	timer: NodeJS.Timer | null
}
const initialState: StateStore = {
	info: {
		state: 0,
		playback_duration: '',
		file_id: '',
		name: '',
		vrs_id: '',
		duration: '',
		dual_stream: 0,
		create_time: '',
	},
	selectVideoFile: null,
	progress: 0,
	timer: null,
}
export const store = createVanilla<PlayVideoStore>((set, get) => ({
	...initialState,
	update: (d) => set({ ...d }),
	reset: () => set(initialState),
	fetchInfo: async (flag = true) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let data = await fetchGetRecordPlayInfo(meetingMoid)
		// console.log(data, 'data----------11-------------')
		if (data) {
			set({ info: data as FetchPlayVideoInfo })
		} else {
			flag && Alert(t('获取会议放像信息失败'))
		}
	},
	isClearTimer: () => {
		let timer = get().timer
		if (timer) {
			clearInterval(timer as unknown as string)
			set({ timer: null })
		}
	},
	setInfo: (videoInfo) => {
		set({ info: videoInfo })
	},
	setSelectVideoFile: (row) => {
		set({ selectVideoFile: row as FetchPlayVideoFile })
	},
	setProgress: (data) => {
		set({ progress: data })
	},
	onDragProgress: (_playback_duration) => {
		let playVideoBackInfo = get().info
		if (playVideoBackInfo) {
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			fetchPostRecordProgress(meetingMoid, { ...playVideoBackInfo, playback_duration: _playback_duration })
		}
	},
	/**mcc_message_play_status 推送时会调用 usePlayVideoStore.getState().changePlayStatus(data)*/
	changePlayStatus: (d) => {
		// console.log(data, 'data------推送----------99')
		let data = get().info
		if (d.state !== 0) {
			let _result = Object.assign({}, data, {
				state: d.state || 0,
				name: d.name || '',
				duration: d.duration || '',
				playback_duration: d.playback_duration || '',
				dual_stream: d.dual_stream || 0,
			})
			data = _result as unknown as FetchPlayVideoInfo
		} else if (data) {
			data.state = 0
			data.playback_duration = '0'
		}
		let state = data?.state ?? 0
		switch (state) {
			case 2: //正在放像
				get().isClearTimer()
				get().startPlay(data?.duration ?? '0')
				break
			case 1: //暂停放像
				get().pausePlay()
				break
			case 0: //未放像
				get().stopPlay()
				break
			default:
				get().isClearTimer()
				break
		}
		if (data) {
			get().setInfo({
				...data,
			})
		}
	},
	/**点击开始录像按钮 */
	onStartPlay: () => {
		let playVideoBackInfo = get().info
		if (playVideoBackInfo) {
			get().checkConflict(() => startMeetingPlayback(playVideoBackInfo as FetchPlayVideoInfo))
		}
	},
	/**开始录像 */
	startPlay: (duration) => {
		get().timer = setInterval(function () {
			if (duration !== '0') {
				let playVideoBackInfo = get().info as FetchPlayVideoInfo
				let _playback_duration = String(parseInt(playVideoBackInfo?.playback_duration ?? '0'))
				let _duration = duration || (playVideoBackInfo?.duration ?? '0')
				let percent = getPercent(_playback_duration, _duration)
				let playback_duration = _duration
				if (percent < 100) {
					playback_duration = String(parseInt(playVideoBackInfo?.playback_duration ?? '0') + 1)
					if (
						Number(playback_duration) > Number(_duration) ||
						Number(playback_duration) === Number(_duration)
					) {
						playback_duration = _duration
					}
				}
				get().setInfo({
					...playVideoBackInfo,
					playback_duration: playback_duration,
				})
			}
		}, 1000)
	},
	/**点击停止放像按钮 */
	onStopPlay: () => {
		let playVideoBackInfo = get().info
		if(playVideoBackInfo){
			if(!playVideoBackInfo.vrs_id){
				get().setInfo({
					state: 0,
					playback_duration: '',
					file_id: '',
					name: '',
					vrs_id: '',
					duration: '',
					dual_stream: 0,
					create_time: '',
				})
			}
		}
		stopMeetingPlayback()
	},
	/**停止放像按钮 */
	stopPlay: () => {
		get().isClearTimer()
		let playVideoBackInfo = get().info as FetchPlayVideoInfo
		get().setInfo({
			...playVideoBackInfo,
			playback_duration: '0',
		})
	},
	/**点击暂停放像按钮 */
	onPausePlay: () => {
		pauseMeetingPlayback()
	},
	/**暂停放像按钮 */
	pausePlay: () => {
		get().isClearTimer()
	},
	/**点击继续放像按钮 */
	onContinuePlay: () => {
		get().checkConflict(() => resumeMeetingPlayback())
	},
	checkConflict: (callback) => {
		let mixMode = mccStore.getState().mixMode // 0 1 2
		let voiceInspireState = mccStore.getState().mccInfo.voiceInspireState
		let isMix: boolean = mixMode !== 0
		let isVoice: boolean = !!voiceInspireState
		if (!isMix && !isVoice) {
			callback()
		} else if (isMix && !isVoice) {
			confirmModal({
				msg: t('混音已开启，与放像声音冲突，是否需要关闭混音？'),
				onOk: () => stopMix(mixMode, callback),
				onCancel: () => callback(),
				okText: t('关闭混音'),
				cancelText: t('保持混音'),
			})
		} else if (!isMix && isVoice) {
			confirmModal({
				msg: t('语音激励已开启，与放像声音冲突，是否需要关闭语音激励？'),
				onOk: () => voiceInspire(callback),
				okText: t('关闭语音激励'),
				cancelText: t('保持语音激励'),
			})
		} else if (isMix && isVoice) {
			confirmModal({
				msg: t('混音和语音激励均已开启，与放像声音冲突，是否需要关闭混音和语音激励？'),
				onOk: () => voiceInspireAndStopMix(mixMode, callback),
				okText: t('关闭'),
				cancelText: t('保持'),
			})
		}
	},
}))
export const usePlayVideoStore = create(store)
